package com.lpssfxy.service.impl;

import com.lpssfxy.bean.R;
import com.lpssfxy.dao.UserRepository;
import com.lpssfxy.entity.User;
import com.lpssfxy.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserRepository userRepository;

    public R getUserList() {
        return R.ok().data("data",userRepository.findAll());
    }

    /**
     * 通过用户名和密码查找指定的User
     * @param user
     * @return
     */
    public R getUserByNameAndPwd(User user) {
        Optional<User> optionalUser = userRepository.findByUsernameAndPassword(user.getUsername(),user.getPassword());
        if (optionalUser.isPresent()) {
            return R.ok().data("data", optionalUser.get());
        }
        return R.error().message("该用户不存在");
    }

    /**
     * 根据userId查询一个User
     * @param userId
     * @return
     */
    public R getUserById(Integer userId) {
        Optional<User> optionalUser = userRepository.findByUserId(userId);
        if (optionalUser.isPresent()) {
            return R.ok().data("data", optionalUser.get());
        }
        return R.error().message("该用户不存在");
    }

    /**
     * 增加一个用户
     * @param user
     * @return
     */
    public R addNewUser(User user) {
        Optional<User> optionalUser = userRepository.findByUserId(user.getUserId());
        if (optionalUser.isPresent()) {
            return R.error().message("该用户已存在");
        }
        userRepository.save(user);
        return R.ok().message("添加用户成功~");
    }

    // 新增一批用户，用于后续联调测试时使用
    @Override
    public R addBatchUsers() {
        List<User> userList = new ArrayList<>();
        for (int i = 0; i < 20; i++) {
            User user = new User();
            user.setUsername("testUser"+ i);
            user.setPassword("123456");
            userList.add(user);
        }
        List<User> resultList = userRepository.saveAll(userList);
        return R.ok().data("data",resultList);
    }

    //更新用户
    public R updateUser(User user) {
        user.setUpdateTime(new Date()); //设置更新时间
        return R.ok().data("data",userRepository.save(user));
    }
    //删除用户
    public R deleteUser(Integer userId) {
        userRepository.deleteById(userId);
        return R.ok().message("删除用户成功~");
    }
}
